package region;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 构建树结构工具类
 */
public class TreeUtil {

    /**
     * 根据反射获取属性值
     * @param t 实体对象
     * @param fieldName 属性名称
     */
    private static<T> Object getFieldValue(T t,String fieldName){
        Field field = ReflectUtil.getField(t.getClass(), fieldName);
        return ReflectUtil.getFieldValue(t, field);
    }

	/**
     * 获取树结构
     * @param list 数据
     */
    public static<T> List<T> buildTree(List<T> list) {
        return buildTree(list, "0","parentId");
    }

    /**
     * 获取树结构
     * @param list 数据
     * @param pId 父级id
     * @param fieldName 父级字段名称
     */
    public static<T> List<T> buildTree(List<T> list,String pId,String fieldName) {
        List<T> root= new ArrayList<>();
        Iterator<T> it = list.iterator();
        while (it.hasNext()) {
            T t = it.next();
            String parentId = getFieldValue(t,fieldName).toString();
            if (parentId.equals(pId)) {
                root.add(t);
                //it.remove();
            }
        }
        getChild(root, list,fieldName);
        return root;
    }

    /**
     * 递归子节点
     */
    public static<T> void getChild(List<T> root,List<T> list,String fileName){
        try {
            for (T nav : root) {
                String id = getFieldValue(nav,"id").toString();
                List<T> childList = buildTree(list, id,fileName);
                getChild(childList, list,fileName);
                Field child = ReflectUtil.getField(nav.getClass(), "children");
                child.set(nav,childList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
